<template>
  <view>
    <!-- 购物车里面存在商品 -->
    <view class="cart-container" v-if="cart.length !== 0">
      <!-- 收货地址组件 -->
      <my-address></my-address>
      <view class="cart-list">
        <!-- 左侧图标 -->
        <uni-icons type="shop" size="18"></uni-icons>
        <!-- 描述文本 -->
        <text class="cart-title-text">购物车</text>
      </view>
     <uni-swipe-action>
       <block v-for="(goods, index) in cart" :key="index">
         <uni-swipe-action-item :rightOptions="options" @click="swipeActionClickHandler(goods)">
           <my-goods :item="goods" :showRadio="true" @radio-change="radioChangeHandler" @num-change="numberChangeHandler"></my-goods>
         </uni-swipe-action-item>
       </block>
     </uni-swipe-action>
    </view>
    
    <!-- 无商品时 -->
    <view class="empty-cart" v-else>
      <text>空空如也</text>
    </view>
  </view>
</template>

<script>
  import { mapGetters, mapState, mapMutations } from 'vuex'
  import badgeMix from '@/mixins/tabbar-badge.js'
  export default {
    mixins: [badgeMix],
    data() {
      return {
        options: [
          {
            text: '删除',
            style: {
               backgroundColor: '#C00000'
            }
          }
        ]
      };
    },
    computed: {
      ...mapGetters('m_cart', ['total']),
      ...mapState('m_cart', ['cart'])
    },
    onShow() {
      // 在页面刚显示出来的时候,设置数字图标
      this.setBadge()
    },
    methods: {
      ...mapMutations('m_cart', ['updateGoodsState', 'updateGoodsCount', 'updateGoods']),
      setBadge() {
        // uni.setTabBarBadge() 方法,为购物车设置右上角的徽标
        uni.setTabBarBadge({
          // 索引
          index: 2,
          // text 的值必须为字符串
          text: this.total + ''
        })
      },
      radioChangeHandler(e) {
        // console.log(e)
        this.updateGoodsState(e)
      },
      numberChangeHandler(e) {
        // 拿到变化后的数值
        this.updateGoodsCount(e)
        
      },
      swipeActionClickHandler(goods) {
        this.updateGoods(goods.goods_id)
      }
    },
    watch: {
      total() {
        this.setBadge()
      }
    }
  }
</script>

<style lang="scss">
  .cart-container {
    padding-bottom: 50px;
  }
.cart-list {
  height: 40px;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-left: 5px;
  border-bottom: 1px solid #efefef;
  
  .cart-title-text {
    margin-left: 10px;
  }
}
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 150px;
}
</style>
